/******************************************************************************
 *
 *       Filename:  getnal.c
 *
 *    Description:  get nal unit
 *
 *        Version:  1.0
 *        Created:  2017年12月21日 12时34分59秒
 *       Revision:  none
 *       Compiler:  gcc
 *
 *         Author:  yangkun (yk)
 *          Email:  xyyangkun@163.com
 *        Company:  yangkun.com
 *
 *****************************************************************************/
#include <stdio.h>
#include <stdlib.h>

#define PACKET_BUFFER_END            (unsigned int)0x00000000
static int FindStartCode2 (unsigned char *Buf)
{
	// printf("Buf:%#X %#X %#x %#X\n", Buf[0], Buf[1], Buf[2], Buf[3]);
	if(Buf[0]!=0 || Buf[1]!=0 || Buf[2] !=1) 
		return 0; //判断是否为0x000001,如果是返回1
	else
		return 1;
}

static int FindStartCode3 (unsigned char *Buf)
{
	if(Buf[0]!=0 || Buf[1]!=0 || Buf[2] !=0 || Buf[3] !=1) 
		return 0;//判断是否为0x00000001,如果是返回1
	else 
		return 1;
}
/* 
 * desp: 获取spspps信息
 * framebuf: 帧缓冲区
 * framesize: 帧大小
 * sp_size   psppps的大小
 * return 0成功,其它值失败
 */
int get_spspps(unsigned char *framebuf, unsigned int framesize, 
		unsigned int *sp_size)
{
	unsigned int pos = 0;
	int StartCodeFound, rewind;
	unsigned char *Buf;
	int info2=0, info3=0;

	Buf = (unsigned char *)framebuf;

	info2 = FindStartCode2(Buf); // 判断是否为0x000001
	if(info2 != 1) 
	{
		info3 = FindStartCode3 (Buf);//判断是否为0x00000001
		if (info3 != 1)//如果不是，返回-1
		{ 
			printf("just for debug==========\n");
			return -2;
		}
		else 
		{
			//如果是0x00000001,得到开始前缀为4个字节
			pos = 4;
		}
	}
	else
	{
		//如果是0x000001,得到开始前缀为3个字节
		pos = 3;
	}

	//查找下一个开始字符的标志位
	StartCodeFound = 0;
	info2 = 0;
	info3 = 0;

	while(!StartCodeFound)
	{
		pos++;
		if (pos>=framesize)
		{
			printf("ERROR: pos big than framesize\n");
			return -3;
		}
		info3 = FindStartCode3(&Buf[pos-4]);//判断是否为0x00000001
		if(info3 != 1)
			info2 = FindStartCode2(&Buf[pos-3]);//判断是否为0x000001

		StartCodeFound = (info2 == 1 || info3 == 1);
		if (StartCodeFound)
		{
			pos++;
			printf("===============debug!!!!%#X  %#X\n", Buf[pos-1], Buf[pos]);
			if((0x1f&(Buf[pos-1]))== 0x08 || \
					(0x1f&(Buf[pos-1]))== 0x05 || \
					(0x1f&(Buf[pos-1]))== 0x06 )
			{
				printf("found !!! pos=%d      %d\n", pos, *sp_size);
				*sp_size = pos - 1;
				break;
			}
		}

	// exit(0);
	}

	return 0;
error:
	return -1;
}
